import { Component, OnInit, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
import axios from 'axios';
import { NzMessageService } from 'ng-zorro-antd/message';

@Component({
  selector: 'app-screen-recording',
  templateUrl: './screen-recording.component.html',
  styleUrls: ['./screen-recording.component.less']
})


export class ScreenRecordingComponent implements OnInit, OnDestroy {

  constructor(
    private http: HttpClient,
    private message: NzMessageService,
  ) { }


  msg: any = '333';

  async handleStart() {

    // console.log(axios, 'axios==');
    // try {
    //   const res = await axios.post(`http://localhost:8089/screen/record/start`);
    //   console.log(res, 'res==');
    // } catch (error) {
    //   this.isRecording = true;
    //   console.error('Error starting recording:', error);
    //   this.message.error('录制失败，请检查后端服务是否启动');
    // }
    await axios.post(`http://localhost:8089/screen/record/start`)
    // console.log(res, 'res==');

    // console.log(environment.apiUrl, 'apiUrl==');

  }

  handleStop() {
    axios.post(`http://localhost:8089/screen/record/stop`).then()
  }

  // ==
  // 录制状态
  isRecording = false;
  recordingStatus = '准备录制';

  // 计时器相关
  recordingTime = 0;
  timer: any = null;
  displayTime = '00:00:00';

  // 最终录制时长
  finalDuration = '';

  ngOnInit() { }

  ngOnDestroy() {
    // 组件销毁时清除计时器
    this.stopTimer();
  }

  // 开始录制
  async startRecording() {
    // try {
    //   const res = await axios.post(`http://localhost:8089/screen/record/start`);
    //   console.log(res, 'res==');
    // } catch (error) {
    //   console.error('Error starting recording:', error);
    //   this.message.error('录制失败，请检查后端服务是否启动');
    //   return;
    // }
    if (this.isRecording) return;
    this.handleStart();
    console.log('开始录制成功');
    this.isRecording = true;
    this.recordingStatus = '录制中';
    this.startTimer();


    // this.http.post(`${environment.apiUrl}/screen/record/start`, {})
    //   .subscribe({
    //     next: (response) => {
    //       console.log('开始录制成功', response);
    //       this.isRecording = true;
    //       this.recordingStatus = '录制中';
    //       this.startTimer();
    //     },
    //     error: (error) => {
    //       console.error('开始录制失败', error);
    //       alert('开始录制失败，请检查后端服务');
    //     }
    //   });
  }

  // 结束录制
  stopRecording() {
    if (!this.isRecording) return;

    console.log('结束录制成功');
    this.isRecording = false;
    this.recordingStatus = '已结束录制';
    this.finalDuration = this.displayTime; // 保存最终时长
    // console.log(this.finalDuration, 'finalDuration==');

    this.stopTimer();
    this.resetTimer(); // 可选：重置计时器
    this.handleStop();

    // this.http.post(`${environment.apiUrl}/screen/record/stop`, {})
    //   .subscribe({
    //     next: (response) => {
    //       console.log('结束录制成功', response);
    //       this.isRecording = false;
    //       this.recordingStatus = '已结束录制';
    //       this.finalDuration = this.displayTime; // 保存最终时长
    //       this.stopTimer();
    //       this.resetTimer(); // 可选：重置计时器
    //     },
    //     error: (error) => {
    //       console.error('结束录制失败', error);
    //       alert('结束录制失败，请检查后端服务');
    //     }
    //   });
  }

  // 启动计时器
  private startTimer() {
    this.recordingTime = 0;
    this.updateDisplayTime();

    this.timer = setInterval(() => {
      this.recordingTime++;
      this.updateDisplayTime();
    }, 1000);
  }

  // 停止计时器
  private stopTimer() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }

  // 重置计时器（可选）
  private resetTimer() {
    this.recordingTime = 0;
    this.displayTime = '00:00:00';
    // this.finalDuration = '';
  }

  // 更新显示时间（格式：HH:MM:SS）
  private updateDisplayTime() {
    const hours = Math.floor(this.recordingTime / 3600);
    const minutes = Math.floor((this.recordingTime % 3600) / 60);
    const seconds = this.recordingTime % 60;

    this.displayTime =
      `${this.padZero(hours)}:${this.padZero(minutes)}:${this.padZero(seconds)}`;
  }

  // 补零函数
  private padZero(num: number): string {
    return num.toString().padStart(2, '0');
  }

  // 获取状态样式类
  getStatusClass(): string {
    return this.isRecording ? 'status-recording' : 'status-stopped';
  }
}
